#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>

//      命令行参数(4)
//          argv[1]: 元素的个数(值在3-31之间)
//          argv[2]: "1"表示时集合有效
//                   "0"表示时集合无效
//          argv[3]: "1"表示集合有解
//                 : "0"表示集合无解

void swap(int * a,int *b){

    int tmp = *a;
    *a = *b;
    *b = tmp;
}

void saveToFile(int * arr,int kval,int num){

    FILE * fptr = fopen("input.txt","w");
    if(NULL == fptr){

        printf("open file failed.\n");
        return;
    }
    fprintf(fptr,"%d ",kval);
    int index = 0;
    for(index=0;index<num;index++){

        fprintf(fptr,"%d ",arr[index]);
    }
}

void shuffleArray(int * arr,int num){

    int index1,index2,index3;
    for(index1 = 0;index1 < 1000;index1++){

        index2 = rand() % num;
        index3 = rand() % num;
        swap(&arr[index2],&arr[index3]);
    }
}

void printArray(int * arr,int num,int kval){

    printf("key value = %d.\n",kval);
    int index = 0;
    for(index = 0;index < num;index++){

        printf("%d ",arr[index]);
    }   
    saveToFile(arr,kval,num);
}

int main(int argc,char * argv[]){

    // -要先对命令行进行解析
    if(argc < 4){

        printf("need four command argv.\n");
        return EXIT_FAILURE;
    }
    int numInt = (int)strtol(argv[1],NULL,10);
    int isValid = (int)strtol(argv[2],NULL,10);
    int hasSol = (int)strtol(argv[3],NULL,10);

    // -超出所限制的范围
    if((numInt < 3) || (numInt) > 31){

        printf("number integer to litte or to big.\n");
        return EXIT_FAILURE;
    }
    // -既不为1 也不为0 表示这个集合是否有解不明确
    if((hasSol!=1) && (hasSol!=0)){

        printf("if has solution isn't smart.\n");
        return EXIT_FAILURE;
    }
    // -随机种子
    srand(time(NULL));

    int kval = 0;
    int * arr = malloc(sizeof(int) * numInt);
    int index = 0;

    arr[0] = rand()%100;
    for(index = 1;index < numInt;index++){

        arr[index] = arr[index-1] + (rand()%10000) + 1;
    }
    // -集合无效
    if(0 == isValid){

        if(rand() % 2 == 0){

            // -使得两个元素的值相同
            arr[numInt-1] = arr[0];
        }else{

            // -使得一个元素的值为负数
            arr[0] = -(rand()%1000);
        }
        // -当数列无效时为不相关的
        kval = rand() % 10000 + 1;
    }else{

        for(index = 0;index < numInt;index++){

            // -无解
            if(0 == hasSol){

                kval += arr[index] + 1;
            }else{

                if(rand() % 3 == 1){

                    kval += arr[index];
                }
            }
        }
        if(0 == kval){

            kval = arr[0];
        }
    }
    shuffleArray(arr,numInt);
    printArray(arr,numInt,kval);
    free(arr);
    return EXIT_SUCCESS;
}